package redis

import (
	"encoding/gob"
	"goshell.straysh.com/internal/conf"
	"strconv"
	"sync"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"golang.org/x/oauth2"
)

var sessionInitOnce sync.Once

// NewSession 实例化session
func NewSession(cfg *conf.Session) sessions.Store {
	sessionInitOnce.Do(func() {
		gob.Register(&oauth2.Token{})
	})

	//b, err := base64.StdEncoding.DecodeString(cfg.Secret)
	//if err != nil {
	//	panic(err)
	//}

	store, err := redis.NewStoreWithDB(10, "tcp", cfg.Addr, cfg.Password, strconv.Itoa(cfg.DB), []byte(cfg.Secret))
	if err != nil {
		panic(err)
	}
	store.Options(sessions.Options{
		MaxAge:   24 * 60 * 60,
		HttpOnly: true,
	})
	if err := redis.SetKeyPrefix(store, "session:"); err != nil {
		panic(err)
	}
	return store
}
